package com.koala.barcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.oned.Code128Writer;

public class BarCodeAgent {
	
	public static final String JPG_IMAGE="jpg";
	public static final String BMP_IMAGE="bmp";
	public static final String JPEG_IMAGE="jpeg";
	public static final String WMBP_IMAGE="wmbp";
	public static final String PNG_IMAGE="png";
	public static final String GIF_IMAGE="gif";
	
	public BarCodeAgent() {
		
	}
	
	public void write(int width, int height, String imageFormat, String text, String fileName, String outputPath){
		
		try {
			
			BitMatrix bitMatrix = new Code128Writer().encode(text, BarcodeFormat.CODE_128, 100, 50, null);
			MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File(outputPath+"/"+fileName+"."+imageFormat))); 
			
		} catch (WriterException e) {
			System.out.println("Error de escritura");
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			System.out.println("error localizando el archivo");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("error de IO");
			e.printStackTrace();
			
		}  
		
	}
	
	public String Read(String path2File){
		
		try {
			InputStream barCodeInputStream = new FileInputStream(path2File);
			BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); 
			
			LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); 
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
			Reader reader = new MultiFormatReader();  
			Result result = reader.decode(bitmap);
			
			return result.getText();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ChecksumException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return null;
		
	}

}
